// 足球运动员
// 足球运动员排序

#include <iostream>
#include <iomanip>
#include <fstream>
#include <algorithm>
#include <string.h>
using namespace std;

class FPlayer {
private:
    int weight, feet, inches, totalInches;
    char name[25];

public:
    FPlayer() { cout << "构造函数\n"; }
    void SetName(const char* n) { strcpy(name, n); }
    void SetWeight(int w) { weight = w; }
    void SetHeight(int feet, int inches) {
        this->feet = feet;
        this->inches = inches;
    }

    void WriteInfo();
    bool operator>(FPlayer rhs);
};

int ReadFootballPlayers(const char* filename, FPlayer team[], int* total);
void SortEm(FPlayer team[], int total);

int main() {
    FPlayer team[5];
    cout << "给运动员对象排序\n";
    cout << "按回车键继续:";

    char enter;
    cin.get(enter);

    int total;
    int error = ReadFootballPlayers("ch09/Players.dat", team, &total);
    if (error) {
        cout << "无法找到文件\n";
        exit(1);
    }

    cout << "Players.dat文件中的原始数据为:\n";
    for_each(team, team+total, [](auto& p) { p.WriteInfo(); });

    SortEm(team, total);

    cout << "\n运动员排序后为:\n";
    for_each(team, team+total, [](auto& p) { p.WriteInfo(); });

    cout << "这些家伙真强壮\n";
}

int ReadFootballPlayers(const char* filename, FPlayer team[], int* total) {
    ifstream input(filename);
    if (!input) {
        return 1;
    }

    char buf[50];
    input.getline(buf, 50);
    *total = atoi(buf);

    for (int i = 0; i < *total; i++) {
        input.getline(buf, 50);
        team[i].SetName(buf);

        int weight, feet, inches;
        input >> feet >> inches >> weight;

        char junk; // 丢弃
        input.get(junk);

        team[i].SetWeight(weight);
        team[i].SetHeight(feet, inches);
    }

    // 不需要，离开作用域会自动close
    // input.close();

    return 0;
}

void FPlayer::WriteInfo() {
    cout << setw(25) << name
        << setw(8) << feet << "'"
        << setw(8) << inches << "\""
        << setw(8) << weight << " 磅\n";
}

bool FPlayer::operator>(FPlayer rhs) {
    if (feet > rhs.feet) {
        return true;
    }
    if (feet < rhs.feet) {
        return false;
    }

    if (inches > rhs.inches) {
        return true;
    }
    if (inches < rhs.inches) {
        return false;
    }

    return weight > rhs.weight;
}

void SortEm(FPlayer team[], int total) {
    sort(team, team+total, [](auto &lhs, auto &rhs) {
        return rhs > lhs;
    });
}